<?php
/**
 * Create by 11li
 * Date 2020/2/20
 * Time 15:58
 *
 */

namespace app\api\controller\v1;


use app\common\controller\Api;
use app\common\service\PromoterService;

class Visitor extends Api
{
	
	/**
	 * 进入
	 */
	public function enter(){
		$model = new \app\common\model\Visitor();
		$data = $this->request->post();
		$data['user_id'] = $this->auth->id;
		$data['params'] = isset($data['params']) ? json_encode($data['params']): '';
		
		if($data['share_user_id'] && $data['share_user_id'] != $data['user_id']) {
			$row = $model->where(['share_user_id' => $data['share_user_id'], 'user_id' => $data['user_id']])
				->find();
			if(!$row) {
				$promoterObj = (new PromoterService())->addVisibleNumber($data['share_user_id']);
			}
			
		}
		
		$res = $model->isUpdate(false)
			->allowField(true)
			->save($data);
		if($res) {
			
			
			$this->success('记录成功', ['id' => $model->getLastInsID()]);
		} else {
			$this->error('记录出错');
		}
	}
	
	/**
	 * 离开
	 */
	public function leave(){
		$id = $this->request->get('id');
		!$id && $this->error('参数错误');
		
		$model = new \app\common\model\Visitor();
		$row = $model->find($id);
		!$row && $this->error('记录不存在');
		
		$res = $model->save(['duration' => time()-$row['create_time'], 'leave_time' => time()], ['id' => $id]);
		if($res !== false) {
			$this->success('记录成功');
		} else {
			$this->error('记录出错');
		}
	}
}